import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { NavBar, Space, Toast, SearchBar, PullToRefresh } from 'antd-mobile'
import  {http,host,port} from '../utils/host'
// 定义Topic接口
interface Topic {
  _id: string;
  title: string;
  hot: number;
  // 根据实际数据结构添加其他字段
}

const TopicSquare: React.FC = () => {
  const [topics, setTopics] = useState<Topic[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [filteredTopics, setFilteredTopics] = useState<Topic[]>([]);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const navigate = useNavigate();

  // 随机排序函数
  const shuffleArray = (array: Topic[]): Topic[] => {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  };

  useEffect(() => {
    const fetchTopics = async (): Promise<void> => {
      try {
        setLoading(true);
        // 使用绝对路径访问后端API
        const response = await axios.get(`${http}${host}${port}/hua/detail`);
        // 确保topics始终为数组
        let data = Array.isArray(response.data) ? response.data : [];
        // 随机排序
        data = shuffleArray(data);
        setTopics(data);
        setFilteredTopics(data);
        setError(null);
      } catch (err) {
        console.error('获取话题数据失败:', err);
        setError('获取话题失败，请稍后重试');
        setTopics([]);
        setFilteredTopics([]);
      } finally {
        setLoading(false);
      }
    };

    fetchTopics();
  }, []);

  // 搜索功能
  useEffect(() => {
    if (searchQuery) {
      const filtered = topics.filter(topic =>
        topic.title.toLowerCase().includes(searchQuery.toLowerCase())
      );
      setFilteredTopics(filtered);
    } else {
      setFilteredTopics(topics);
    }
  }, [searchQuery, topics]);

  // 处理搜索
  const handleSearch = (value: string): void => {
    setSearchQuery(value);
  };

  // 清除搜索
  const clearSearch = (): void => {
    setSearchQuery('');
  };

  // 下拉刷新
  const onRefresh = (): void => {
    setRefreshing(true);
    // 模拟刷新延迟
    setTimeout(() => {
      const fetchTopics = async (): Promise<void> => {
        try {
          // 使用绝对路径访问后端API
          const response = await axios.get(`${http}${host}${port}/hua/detail`);
          // 确保topics始终为数组
          let data = Array.isArray(response.data) ? response.data : [];
          // 随机排序
          data = shuffleArray(data);
          setTopics(data);
          setFilteredTopics(data);
          setError(null);
        } catch (err) {
          console.error('获取话题数据失败:', err);
          setError('获取话题失败，请稍后重试');
          setTopics([]);
          setFilteredTopics([]);
        } finally {
          setRefreshing(false);
        }
      };

      fetchTopics();
    }, 100);
  };

  return (
    <div className="topic-square-container">
      <NavBar onBack={() => navigate(-1)} style={{marginTop: '0px',marginLeft: '0px',marginBottom:"20px"}}>话题广场</NavBar>

      {/* 搜索区域 */}
      <SearchBar
        placeholder="请输入搜索关键词"
        value={searchQuery}
        onChange={handleSearch}
        onClear={clearSearch}
        className="search-bar"
      />

      {/* 内容区域 */}
      {loading ? (
        <div className="loading-state">
          <div className="spinner"></div>
          <p>加载中...</p>
        </div>
      ) : error ? (
        <div className="error-state">
          <p>{error}</p>
          <button onClick={() => window.location.reload()} className="retry-button">重试</button>
        </div>
      ) : filteredTopics.length === 0 ? (
        <div className="no-results">
          <p>暂无话题数据</p>
          {searchQuery && <p className="search-tip">换个关键词试试吧</p>}
        </div>
      ) : (
        <div className="pull-refresh-wrapper">
          <PullToRefresh
            refreshing={refreshing}
            onRefresh={onRefresh}
            className="pull-refresh-container"
          >
            <div className="topics-list">
              {filteredTopics.map((topic) => (
                <div
                  key={topic._id}
                  className="topic-item"
                  onClick={() => navigate('/topic-detail/' + topic._id)}
                  style={{ cursor: 'pointer' }}
                >
                  <span className="topic-hashtag">{topic.title}</span>
                  <span className="topic-hotness">{topic.hot}W热度</span>
                </div>
              ))}
            </div>
          </PullToRefresh>
        </div>
      )}

      {/* 底部区域 */}
      <div className="bottom-line">
        <p>我是有底线的</p>
      </div>
    </div>
  );
};

// 样式定义
const styles = `
.topic-square-container {
  min-height: 100vh;
  padding: 20px;
  background-color: white;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.pull-refresh-wrapper {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.pull-refresh-container {
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 20px;
  /* 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}

/* 滚动条滑块 */
.pull-refresh-container::-webkit-scrollbar {
  width: 6px;
}

.pull-refresh-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.pull-refresh-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 10px;
}

.pull-refresh-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.topics-list {
  width: 100%;
}

.search-bar {
  margin-bottom: 24px;
  background-color: #ffffff;
  border-radius: 24px;
  overflow: hidden;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.retry-button {
  margin-top: 12px;
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #888;
}

.search-tip {
  margin-top: 8px;
  font-size: 14px;
}

.pull-refresh-wrapper {
  flex: 1;
  overflow: hidden;
}

.pull-refresh-container {
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 20px;
}

.topics-list {
  width: 100%;
}

.topic-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}

.topic-hashtag {
  font-size: 16px;
  color: #333;
}

.topic-hotness {
  font-size: 14px;
  color: #888;
  background-color: #f5f5f5;
  padding: 4px 10px;
  border-radius: 12px;
}

.bottom-line {
  text-align: center;
  margin-top: 20px;
  padding: 10px;
  font-size: 12px;
  color: #ccc;
}
`;

// 将样式添加到文档头部
if (typeof document !== 'undefined') {
  const styleSheet = document.createElement('style');
  styleSheet.type = 'text/css';
  styleSheet.innerText = styles;
  document.head.appendChild(styleSheet);
}

export default TopicSquare;